import React, { Component } from 'react';
import {
  StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, PixelRatio
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import PickerData from '../../../component/common/MonthPicker';
import ToastUtil from '../../../utils/toast';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';

const scale = GLOBAL.SCALE;

export class fundsMail extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      headerTitle: '邮件推送',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
      headerStyle: {  // 头部整体样式 
        elevation: 0,
        borderBottomWidth: 0,
        backgroundColor: style.color.themeColor
      },
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  };

  constructor(props) {
    super(props)
    let { companyId, corpType, companyName, corpId, isForeign } = props.navigation.state.params || {};
    this.state = {
      modalVisible: false,
      time: '',
      count: 0,
      email: '',
      status: 'loading'
    }
    this.pageParams = {
      companyId,
      corpType,
      companyName,
      corpId,
      emails: [],
      isForeign
    }
  }

  async componentWillMount() {
    await this.initPage();
  }
  async initPage() {
    let res = await HTTP.POST(API_GENERATE(API.EMAIL_PUSH_CNT), this.pageParams);
    this.setState({
      count: res.count,
      email: res.email,
      status: 'data'
    })
  }
  async selectTime(time) {
    this.setState({
      time,
      modalVisible: false
    })
  }

  async _pushEmail() {
    this.pageParams.ledgerMonth = this.state.time
    this.pageParams.emails[0] = this.state.email
    if (!this.state.time) {
      ToastUtil.showWarning('请先选择账单月份');
    }
    else if (!this.state.email) {
      ToastUtil.showWarning('没有邮箱不可推送邮件');
    }
    else {
      this.setState({
        status: 'loading'
      })
      let res = await HTTP.POST(API_GENERATE(API.EMAIL_PUSH), this.pageParams);
      if (res) {
        this.setState({
          status: 'data'
        })
        ToastUtil.showSuccess('邮箱推送成功').then(() => {
          this.props.navigation.goBack();
        })
      }
      else {
        this.setState({
          status: 'error'
        })
      }
    }

  }

  render() {
    let { modalVisible, time, email, count, status } = this.state;
    return (
      <View style={styles.container}>
        <View style={{ marginTop: 22 * scale, marginLeft: 12 * scale }}>
          <Text style={{ color: '#CA0202', fontSize: 12 * scale, fontWeight: '600' }}>* 邮件推送，每天仅支持推送3次，当前剩余次数 {count} 次</Text>
        </View>
        <View style={styles.flexBox}>
          <Text style={styles.flexText} >账单月份：</Text>
          <TouchableOpacity onPress={() => {
            this.setState({
              modalVisible: true
            })
          }} style={styles.flexInput}>
            <Text style={[styles.flexInputText, time ? null : { color: '#AEAEAE' }]}>{time ? time : '请选择账单月份，年-月'}</Text>
            <Image source={require('../../../imgs/arrow-left.png')} style={styles.detailImg} />
          </TouchableOpacity>
        </View>
        <View style={styles.flexBox}>
          <Text style={styles.flexText} >接收邮箱：</Text>
          <View style={styles.flexInput}>
            <Text style={[styles.flexInputText, email ? null : { color: '#AEAEAE' }]}>{email ? email : '此处为业务员的邮箱，带入不支持编辑'}</Text>
          </View>
        </View>
        {status === 'loading' ? <PageStatusIndex status={'loading'} onErrorPress={this.initPage} /> : null}
        <TouchableOpacity style={{ position: 'absolute', alignItems: 'center', width: '100%', bottom: 80 * scale }} onPress={() => { this._pushEmail() }}>
          <Image source={require('../../../imgs/clickMailBg.png')} style={{ width: 274 * scale, height: 56 * scale }} />
        </TouchableOpacity>
        <PickerData
          visible={modalVisible}
          onCancel={
            () => {
              this.setState({
                modalVisible: false
              })
            }
          }
          onRequestClose={
            () => {
              this.setState({
                modalVisible: false
              })
            }
          }
          onComfig={(time) => this.selectTime(time)}
        />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray,
  },
  flexBox: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 50 * scale,
    marginHorizontal: 16 * scale
  },
  flexText: {
    color: '#000',
    fontSize: 14 * scale,
    fontWeight: '700'
  },
  flexInput: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#000',
    flex: 1,
    marginRight: 30 * scale,
    paddingBottom: 6 * scale
    // paddingLeft:20*scale
  },
  flexInputText: {
    textAlign: 'center',
    fontSize: 12 * scale
  },
  detailImg: {
    position: 'absolute',
    right: 0,
    top: 3 * scale,
    width: 6 * scale,
    height: 9 * scale,
    tintColor: '#AEAEAE',
    marginLeft: 5 * scale,
    transform: [{ 'rotate': '90deg' }]
  }
})